package com.jinxin.phonecloudmusic.myapplication.fragment.dialogfragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jinxin.phonecloudmusic.myapplication.R;
import com.jinxin.phonecloudmusic.myapplication.adapter.FragmentAdapter;
import com.jinxin.phonecloudmusic.myapplication.entity.GroupBean.Lyrics;
import com.jinxin.phonecloudmusic.myapplication.entity.GroupBean.Play;
import com.jinxin.phonecloudmusic.myapplication.entity.MusicBean.Song;
import com.jinxin.phonecloudmusic.myapplication.entity.MusicBean.SongList;
import com.jinxin.phonecloudmusic.myapplication.event.MusicControlEvent;
import com.jinxin.phonecloudmusic.myapplication.fragment.fra.PlayMusicImageFragment;
import com.jinxin.phonecloudmusic.myapplication.fragment.fra.PlayMusicLyricsFragment;
import com.jinxin.phonecloudmusic.myapplication.fragment.fra.PlayMusicSongsFragment;
import com.jinxin.phonecloudmusic.myapplication.presenter.IPresenter.IMainPagePresenter;
import com.jinxin.phonecloudmusic.myapplication.presenter.PresenterImpl.IMainPagePresentImp;
import com.jinxin.phonecloudmusic.myapplication.utils.RxBus;
import com.jinxin.phonecloudmusic.myapplication.view.IMusicPlayView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

/**
 * Created by ZJ on 2017/10/16 0016.
 * 播放界面
 */

public class PlayInterfaceFragment extends DialogFragment implements IMusicPlayView {
    @BindView(R.id.btn_music_by_list)
    Button btnMusicByList;
    @BindView(R.id.btn_music_play)
    Button btnMusicPlay;
    @BindView(R.id.btn_music_pause)
    Button btnMusicPause;
    @BindView(R.id.btn_music_interface_last)
    Button btnMusicInterfaceLast;
    @BindView(R.id.btn_music_interface_next)
    Button btnMusicInterfaceNext;
    @BindView(R.id.sb_progress)
    SeekBar sbProgress;
    @BindView(R.id.tv_play_music_name)
    TextView tvPlayMusicName;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.vp_fragments1)
    ViewPager vpFragments;
    @BindView(R.id.iv_dot_left)
    ImageView ivDotLeft;
    @BindView(R.id.iv_dot_right)
    ImageView ivDotRight;
    @BindView(R.id.iv_dot_last)
    ImageView ivDotLast;
    @BindView(R.id.left)
    TextView tvLeft;
    @BindView(R.id.right)
    TextView tvRight;

    private PlayMusicImageFragment playMusicImageFragment;
    private PlayMusicLyricsFragment playMusicLyricsFragment;
    private PlayMusicSongsFragment playMusicSongsFragment;

    private int pos;
    private List<SongList> allHotSongs=new ArrayList<>();
    private List<Song> singers=new ArrayList<>();
    private int singerPos;
    private Play play;

    private int sum;
    private int cur;
    private int prass;
    private int a;
    private IMainPagePresenter iMainPagePresenter;
    private boolean slide=false;//滑动过程中：true  否则：false

    private Unbinder unbinder;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.costom);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fra_music_play, container, false);
        unbinder = ButterKnife.bind(this,view);
        //initView(view);
        init();//初始化
        return view;
    }


    private void init() {
        iMainPagePresenter = new IMainPagePresentImp(this);
        //接收数据
        if (getArguments() != null&&null!=getArguments().getSerializable("allSongs")) {
            allHotSongs = (List<SongList>) getArguments().getSerializable("allSongs");
            pos = getArguments().getInt("pos", 0);
            iMainPagePresenter.playMusic("play", allHotSongs.get(pos).getSong_id());
            iMainPagePresenter.playMusicLric("lry", allHotSongs.get(pos).getSong_id());
        }if (getArguments() != null&&null!=getArguments().getSerializable("singers")){
            singers= (List<Song>) getArguments().getSerializable("singers");
            singerPos = getArguments().getInt("pos", 0);
            iMainPagePresenter.playMusic("play", singers.get(singerPos).getSongid());
            iMainPagePresenter.playMusicLric("lry", singers.get(singerPos).getSongid());
        }

        //自动播放下一首功能
        RxBus.getDefault().register(MusicControlEvent.class).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<MusicControlEvent>() {
            @Override
            public void accept(MusicControlEvent event) throws Exception {
                if ((event.getTag()) == 11) {//0:播放包括上下首
                    pos = pos + 1;
                    iMainPagePresenter.playMusic("play", allHotSongs.get(pos).getSong_id());
                }if (event.getTag()==1005){
                    if(null!=getDialog())
                    getDialog().show();
                }
            }
        });

        //viewpager自动切换（图片/歌词）
        ArrayList<Fragment> fragments = new ArrayList<>();
        playMusicSongsFragment = new PlayMusicSongsFragment();
        fragments.add(playMusicSongsFragment);
        playMusicImageFragment = new PlayMusicImageFragment();
        fragments.add(playMusicImageFragment);
        playMusicLyricsFragment = new PlayMusicLyricsFragment();
        fragments.add(playMusicLyricsFragment);

        FragmentAdapter adapter = new FragmentAdapter(getChildFragmentManager(), fragments);
        vpFragments.setOffscreenPageLimit(3);
        vpFragments.setAdapter(adapter);

        vpFragments.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }
            @Override
            public void onPageSelected(int position) {
                Log.e("----positon",position+"");
                if (position == 0) {
                    ivDotLeft.setBackgroundResource(R.drawable.dot_check);
                    ivDotRight.setBackgroundResource(R.drawable.dot);
                    ivDotLast.setBackgroundResource(R.drawable.dot);
                }
                if (position == 1) {
                    ivDotLeft.setBackgroundResource(R.drawable.dot);
                    ivDotRight.setBackgroundResource(R.drawable.dot_check);
                    ivDotLast.setBackgroundResource(R.drawable.dot);
                }
                if (position == 2) {
                    ivDotLeft.setBackgroundResource(R.drawable.dot);
                    ivDotRight.setBackgroundResource(R.drawable.dot);
                    ivDotLast.setBackgroundResource(R.drawable.dot_check);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        vpFragments.setCurrentItem(1);
        //更新进度值
        handler.sendEmptyMessage(1);


        //进度控制
        RxBus.getDefault().register(MusicControlEvent.class).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<MusicControlEvent>() {
            @Override
            public void accept(MusicControlEvent event) throws Exception {
                if ((event.getTag()) == 7) {//7：进度控制
                    slide=false;
                    sum= (int) event.getObj1();
                    cur= (int) event.getObj2();
                    Log.e("7",cur+"");
                }
            }
        });

        //初始化
        sbProgress.setMax(100);//设置最大值
        sbProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                slide=true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                a = (int) ((sum / 100.0) * (seekBar.getProgress()));
                RxBus.getDefault().post(new MusicControlEvent(5, 0, a,""));
            }
        });

        //干掉返回键（暂时这样处理）
        this.getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
            long time=0;
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event){
                if (keyCode == KeyEvent.KEYCODE_SEARCH){
                    if (System.currentTimeMillis() - time > 2000) {
                        Toast.makeText(getActivity(), "双击退出", Toast.LENGTH_SHORT).show();
                        time = System.currentTimeMillis();
                        return true;
                    }else{
                        getDialog().hide();
                        return true;
                    }
                }else {
                    getDialog().hide();
                    return true;
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        sbProgress.setProgress(0);
        super.onDestroy();
        unbinder.unbind();
    }

    @Override
    public void updatePlayState(final Play play) {
        this.play = play;
        RxBus.getDefault().post(new MusicControlEvent(0, getActivity(), play.getBitrate().getFile_link(),""));
        RxBus.getDefault().post(new MusicControlEvent(9, play,"",""));//tag:9 上下首（图片碎片）
        playInfo();
    }

    @Override
    public void updateLric(Lyrics lyrics) {
        RxBus.getDefault().post(new MusicControlEvent(10, lyrics.getLrcContent(),"",""));//tag:10 下一首（歌词碎片）
        //加载歌词
        //lrcView.loadLrc(s.getLrcContent());

    }

    @OnClick({R.id.btn_music_interface_last, R.id.btn_music_interface_next, R.id.btn_music_play, R.id.btn_music_pause, R.id.iv_back})
    public void onclick(View v) {
        switch (v.getId()) {
            case R.id.btn_music_interface_last://上一首
                pos = pos - 1;
                iMainPagePresenter.playMusic("play", allHotSongs.get(pos).getSong_id());
                iMainPagePresenter.playMusicLric("lry", allHotSongs.get(pos).getSong_id());
                break;
            case R.id.btn_music_interface_next://下一首
                pos = pos + 1;
                iMainPagePresenter.playMusic("play", allHotSongs.get(pos).getSong_id());
                iMainPagePresenter.playMusicLric("lry", allHotSongs.get(pos).getSong_id());
                break;
            case R.id.btn_music_play://暂停
                RxBus.getDefault().post(new MusicControlEvent(2, "", "",""));
                btnMusicPlay.setVisibility(View.INVISIBLE);
                btnMusicPause.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_music_pause://对暂停中的音乐继续再播放
                RxBus.getDefault().post(new MusicControlEvent(3, "", "",""));
                btnMusicPlay.setVisibility(View.VISIBLE);
                btnMusicPause.setVisibility(View.INVISIBLE);
                break;
            case R.id.iv_back://返回
                getDialog().hide();
                break;
            default:
                break;
        }
    }

    private void playInfo() {
        //播放时更改按钮图标
        btnMusicPlay.setVisibility(View.VISIBLE);
        btnMusicPause.setVisibility(View.INVISIBLE);
        tvPlayMusicName.setText(play.getSongInfo().getTitle());
    }

    //act上面的seekbar
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1://进度值控制
                    if (slide==false&&null!=sbProgress){
                        RxBus.getDefault().post(new MusicControlEvent(5, 1, "",""));//获取进度
                        prass = (int) (cur/ (sum * 1.0) * 100);
                        if (null!=tvRight&&null!=tvLeft) {
                            tvRight.setText(FormatTime(sum / 1000));
                            tvLeft.setText(FormatTime(cur / 1000));
                        }
                        sbProgress.setProgress(prass);
                    }
                        handler.sendEmptyMessageDelayed(1, 800);//更新seekbar（1秒间隔）
                    break;
                default:
                    break;
            }
        }
    };

    //格式化时间
    /**
     * 局限性歌曲最长时长59:59
     *
     * @param s 单位是秒
     * @return
     */
    private String FormatTime(int s) {
        StringBuffer result = new StringBuffer();
        int a = s / 60;
        int b = s % 60;
        if (a < 10) {
            result.append("0");
        }
        result.append(String.valueOf(a));
        result.append(":");
        if (b < 10) {
            result.append("0");
        }
        result.append(String.valueOf(b));
        return result.toString();
    }
}
